<!DOCTYPE html>
<html class="x-admin-sm">
    <head>
        <meta charset="UTF-8">
        <title>全宗</title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
        <link rel="stylesheet" href="../css/font.css">
        <link rel="stylesheet" href="../css/xadmin.css">
        <link rel="stylesheet" href="../lib/layui/css/dtree.css">
        <link rel="stylesheet" href="../lib/layui/font/dtreefont.css">
        <script src="../lib/layui/layui.js" charset="utf-8"></script>
        <script type="text/javascript" src="../js/xadmin.js"></script>
        <script src="../lib/axios.min.js"></script>
        <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
        <!--[if lt IE 9]>
            <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
            <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>
        <div class="layui-fluid">
            <div class="layui-row layui-col-space10">
                
                <div class="layui-col-xs6">
                    <br/>
                    <form class="layui-form" id="mainForm">
                        <div class="layui-form-item">
                            <label for="id" class="layui-form-label">全宗号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="id" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label for="title" class="layui-form-label">全宗名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="title" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label for="L_repass" class="layui-form-label">
                            </label>
                            <button type="button" class="layui-btn" lay-filter="add" lay-submit="">
                                添加全宗
                            </button>
                            <button type="button" class="layui-btn" lay-filter="save" lay-submit="">
                                保存位置
                            </button>
                        </div>
                    </form>
                    <table id="demo" lay-filter="test"></table>
                </div>
                <div class="layui-col-xs4" id="toolbarDiv">
                    <ul id="demoTree1" class="dtree" data-id="0"></ul>
                </div>
            </div>
        </div>
        <script type="text/html" id="bar">
            <a lay-event="moveup" title="上移" href="javascript:;">
                <i class="layui-icon">&#xe619;</i></a>
            <a lay-event="movedown" title="下移" href="javascript:;">
                <i class="layui-icon">&#xe61a;</i></a>
            <a lay-event="delete" title="删除" href="javascript:;">
                <i class="layui-icon">&#xe640;</i></a>
        </script>
        <script type="text/javascript">
            var tree = []
            axios.get('/api/get_q').then(res=>{
                tree = res.data;
                var gen = [];
                for (var i=0;i<tree.length;i++){
                    if (tree[i].parentId === "0") {
                        gen.push(tree[i]);
                    }
                }

                layui.config({
                    base: '../lib/layui/layui-expand/' //插件路径
                }).extend({
                    enhanceform: 'enhanceform',
                    dtree: 'dtree'
                });
                layui.use(['element', 'dtree', 'table', 'form', 'enhanceform'], function(){
                    var dtree = layui.dtree
                    ,table = layui.table
                    ,form = layui.form
                    ,enhanceForm = layui.enhanceform;
                    var enhance = new enhanceForm({
                        elem: '#mainForm' //表单选择器
                    });
                    //渲染s
                    var kin = {};
                    // function q_gk(pid, qid){
                    //     var pi = pid;
                    //     var qi = qid;
                    //     if(pi == "0"){
                    //         console.log(qi);
                    //         return qi;
                    //     }else{
                    //         axios.post("/api/get_gk", {'pid': pi}).then(res=>{
                    //             pi = res.data.parentId;
                    //             qi = res.data.qid;
                    //             console.log(pi, qi);
                    //             return q_gk(pi, qi);
                    //         })
                    //     }
                    // }
                    var dTree = dtree.render({
                        elem: "#demoTree1"  //绑定元素
                        ,scroll:"#toolbarDiv"
                        ,dataFormat: "list"
                        ,data: tree
                        ,record: true
                        ,skin: "laySimple"
                        ,line: true
                        ,toolbar:true
                        ,toolbarBtn:[
                            [
                                {"label":"节点类型","name":"name1","type":"select","optionsData":function(){
                                    return {"1":"分类节点","2":"档案节点","3":"数据节点","4":"分组节点"};
                                }},
                                
                                {"label":"档案类型","name":"name2","type":"select", "optionsData":function(){
                                    return kin;
                                }},
                                
                                {"value":"新增","name":"name7","type":"submit","defElem":"btn"},
                            ], // 这就是自定义新增中的内容
                            [
                                {"label":"节点类型","name":"name1","type":"select","optionsData":function(){
                                    return {"1":"分类节点","2":"档案节点","3":"数据节点","4":"分组节点"};
                                }},
                                {"label":"档案类型","name":"name2","type":"select","optionsData":function(){
                                    return kin;
                                }},
                                {"value":"保存","name":"name7","type":"submit","defElem":"btn"},
                            ]
                        ],
                        toolbarFun: {
                            loadToolbarBefore: function(buttons, param){
                                var kind = [];
                            
                                if(param.parentId == "0"){
                                    axios.post("/api/get_k_q", {'qid': Number(param.recordData.qid)}).then(res=>{
                                        kind = res.data;
                                        kin = {};
                                        for (var index in kind) {
                                            var key = kind[index].kid;
                                            var value = kind[index].kname;
                                            kin[key] = value;
                                        }
                                    })
                                }else{
                                    axios.post("/api/get_gk", {'pid': param.parentId}).then(res=>{
                                        qi = res.data.qid;
                                        axios.post("/api/get_k_q", {'qid': qi}).then(res=>{
                                            kind = res.data;
                                            kin = {};
                                            for (var index in kind) {
                                                var key = kind[index].kid;
                                                var value = kind[index].kname;
                                                kin[key] = value;
                                            }
                                        })
                                    });
                                }

                                if(!param.leaf){ // 如果是叶子节点
                                    buttons.delToolbar = "";  // 取消删除功能
                                }
                                if(Number(param.level)<2){
                                    buttons.editToolbar = "";
                                    buttons.delToolbar = "";
                                }
                                
                                return buttons; // 将按钮对象返回
                            },
                            editTreeLoad: function(treeNode){
                                var param = treeNode;
                                // 这里的param格式为：  {level:treeNode.level, test:"3"};
                                dTree.changeTreeNodeDone(param); // 配套使用
                            },
                            addTreeNode: function(treeNode){
                                if(treeNode.name1 == "2"){
                                    var tp = treeNode.name2
                                } else{
                                    var tp = treeNode.addNodeName
                                }
                                
                                var node = {
                                    th: -Number(treeNode.name1),
                                    title: treeNode.addNodeName,
                                    id: tp,
                                    parentId: treeNode.parentId
                                }
                                if(node.id !== node.parentId){
                                    axios.post("/api/add_q", node).then(res=>{
                                        dTree.changeTreeNodeAdd(res.data);
                                    })
                                }else{
                                    layer.msg("不能嵌套相同类型的节点！");
                                }
                            },
                            editTreeNode: function(treeNode){
                                console.log(treeNode.recordData.th)
                            },
                            delTreeNode: function(treeNode, $div){
                                axios.post("/api/del_q", {qid:treeNode.recordData.qid}).then(res=>{
                                    dTree.changeTreeNodeDel($div)
                                })
                            }
                        }
                          
                    });
                    //单击节点 监听事件
                    form.on('submit(add)', function(dat){
                        var formData = dat.field;
                        formData.th = tree.length;
                        formData.parentId = "0";
                        console.log(formData)
                        axios.post("/api/add_q", formData).then(res=>{
                            tree.push(res.data)
                            gen.push(res.data)
                            table.reload('demo', {
                                data: gen
                            });
                            dtree.reload('demoTree1', {
                                data: tree
                            })
                        })
                        
                        return false;
                    })
                    form.on('submit(save)', function(){
                        for (var i in gen) {
                            gen[i].th = Number(i);
                            axios.post("/api/up_q", gen[i]);
                        }
                        axios.get("/api/get_q").then(res=>{
                            tree = res.data;
                            dtree.reload('demoTree1', {
                                data: tree
                            })
                        })
                        layer.msg('全宗顺序保存成功！');
                        return false;
                    })

                    table.render({
                        elem: '#demo'
                        ,width: 400
                        ,record: true
                        ,initSort: {
                            field: 'th' //排序字段，对应 cols 设定的各字段名
                        }
                        ,cols: [[
                            {field: 'id', title: '全宗号', event: 'setId', style:'cursor: pointer;'}
                            ,{field: 'title', title: '全宗名称', event: 'setTitle', style:'cursor: pointer;'}
                            ,{field: 'th', title: '顺序'}
                            ,{field: '', title: '操作', toolbar: '#bar'}
                        ]]
                        ,data: gen
                    });
                    table.on('tool(test)', function(obj){
                        var index = Number(obj.tr[0].dataset.index);
                        data = obj.data;
                        switch (obj.event) {
                        case 'moveup':
                            var data = obj.data;
                            if(index!==0){
                                gen[index] = gen.splice(index-1, 1, gen[index])[0];
                            }else{
                                gen.push(gen.shift());
                            }
                            table.reload('demo',{
                                data: gen
                            })
                            break;
                        case 'movedown':
                            if(index!==gen.length-1){
                                gen[index] = gen.splice(index+1, 1, gen[index])[0];
                            }else{
                                gen.unshift(gen.splice(index,1)[0]);
                            }
                            table.reload('demo',{
                                data: gen
                            })
                            break;
                        case 'delete':
                            layer.confirm('确认要删除该全宗吗？',function(){
                                var id = gen[index].qid;
                                axios.post("/api/get_k_q", {qid: Number(id)}).then(res=>{
                                    if (res.data.length > 0){
                                        layer.msg("该全宗下存在档案类型，无法删除！");
                                    }else{
                                        axios.post("/api/del_q", {'qid': id}).then(res=>{                                           
                                            tree.splice(index+1, 1);
                                            obj.del();
                                            layer.msg('删除成功', {icon: 1, time: 1000});
                                        })
                                    }
                                })
                            });
                            break;
                        case 'setId':
                            layer.prompt({
                                formType: 2
                                ,title: '修改 全宗名称 为 ['+ data.title +'] 的全宗号'
                                ,value: data.id
                            }, function(value, index){
                                var old = data.id;
                                data.id = value;
                                axios.post("/api/up_q", data).then(res=>{
                                    layer.close(index);
                                    axios.post("/api/up_pid", {oid:old, nid: value}).then(res=>{
                                        console.log(res.data)
                                    })
                                    obj.update({
                                        id: value
                                    });
                                });
                            });
                            break;
                        case 'setTitle':
                            layer.prompt({
                                formType: 2
                                ,title: '修改 全宗号 为 ['+ data.id +'] 的全宗名称'
                                ,value: data.title
                            }, function(value, index){
                                data.title = value;
                                axios.post("/api/up_q", data).then(res=>{
                                    layer.close(index);
                                    obj.update({
                                        title: value
                                    });
                                });
                            });
                            break;
                        }
                    })
                });
            });
        </script>
    </body>

</html>